/**
 * Created by a1 on 16/4/29.
 */

var url = "http://api.1-blog.com/biz/bizserver/xiaohua/list.do"
var P_MaxId = "maxXhid"
var P_MinId = "minXhid"
var P_Size = "size"
var size = 20

var kId = "xhid"
var kAuthor = "author"
var kContent = "content"
var kImageUrl = "picUrl"

var maxId = 0
var minId = 0

var currentData
var nodeList

$(function() {
    //alert("init")
    init()
    loadList()
})

function init() {
    nodeList = $("#list")
    $(document).on("pageinit","#page_detail",function(){
        initDetail()
    })
}

function loadList() {
    var params = {}
    params[P_MaxId] = maxId
    params[P_MinId] = minId
    params[P_Size] = size
    //alert("params = " + JSON.stringify(params))
    $.getJSON(url, params, function(data) {
        var length = data["detail"].length
        //alert("data = " + length)
        for(var  i = 0; i < length; ++i) {
            addItem(nodeList, i, data["detail"][i])
        }
    })
}

function addItem(parent, index, data) {
    var id = data[kId]
    if(maxId == 0 || id > maxId) {
        maxId = id
    }

    if(minId == 0 || id < minId) {
        minId = id
    }
    //alert(index + " = " + JSON.stringify(data))
    var item = $("<li></li>")
    var content = $("<div class='item'></div>")
    var contentText = $("<div class='content_text'>"+data[kContent]+"</div>")
    var imageUrl = data[kImageUrl]
    var hasImage = (trim(imageUrl) != "")
    if(hasImage) {
        var imageView = $("<img class='content_image' src='"+imageUrl+"'/>")
        item.append(imageView)
        //重置文本与item的size
        content.attr("size", "")
        item.attr("size", "")
    }
    var divider = "<div class='divider'></div>"
    content.append(contentText)
    item.append(content)
    item.append(divider)
    parent.append(item)

    item.click(function() {
        toDetail(data)
    })
}

function toDetail(data) {
    //alert("data = " )
    currentData = data
    $.mobile.changePage("detail.html", { transition: "slidefade" })
}

function initDetail() {
    //alert("initDetail")
    $("#btn_back").click(function(){
        history.back()
    })
    var nodeDetail = $("#detail")
    var text =  currentData[kContent]
    var detailText =  $("<div class='detail_text'>"+text+"</div>")
    nodeDetail.append(detailText)

    var imageUrl =  currentData[kImageUrl]
    //alert("node detail = " + nodeDetail + ", text = " + text + ", imageUrl = " + imageUrl)
    if(trim(imageUrl) != "") {
        var imageView = $("<img class='detail_image' src='"+imageUrl+"'/>")
        nodeDetail.append(imageView)
    }
}
